package com.bing.java.memory;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
/**
 * 内存模型
 * 原子性
 * @author bing
 *
 * 2019年11月9日 下午2:22:39
 * AtomicInteger
 */
public class AtomicExample {
	private AtomicInteger cnt = new AtomicInteger();

	public void add() {
		cnt.incrementAndGet();
	}

	public int get() {
		return cnt.get();
	}

	public static void main(String[] args) throws InterruptedException {
		final int threadSize = 1000;
		AtomicExample example = new AtomicExample(); // 只修改这条语句
		final CountDownLatch countDownLatch = new CountDownLatch(threadSize);
		ExecutorService executorService = Executors.newCachedThreadPool();
		for (int i = 0; i < threadSize; i++) {
			executorService.execute(() -> {
				example.add();
				countDownLatch.countDown();
			});
		}
		countDownLatch.await();
		executorService.shutdown();
		System.out.println(example.get());
	}
}